import express from 'express';
import { body, validationResult } from 'express-validator';
import { ServiceIntegration } from '../models/index.js';
import { authenticateAdmin } from '../middleware/auth.js';
import { success, error as errorResponse } from '../utils/response.js';
import { BusinessError } from '../utils/errors.js';
import { catchAsync } from '../utils/catchAsync.js';
import axios from 'axios';
import config from '../config/index.js';
import SystemKClient from '../utils/systemKClient.js';
import { clearImageUrlTemplateCache } from '../utils/imageUrl.js';

const router = express.Router();

// 获取服务配置列表
router.get('/admin/list',
  authenticateAdmin,
  catchAsync(async (req, res) => {
    const services = await ServiceIntegration.findAll({
      order: [['service_name', 'ASC']]
    });
    
    res.json(success(services, '获取服务配置列表成功'));
  })
);

// 获取指定服务配置
router.get('/admin/:serviceName',
  authenticateAdmin,
  catchAsync(async (req, res) => {
    const { serviceName } = req.params;

    let service = await ServiceIntegration.getByServiceName(serviceName);

    if (!service) {
      // 如果记录不存在，先初始化默认配置
      await ServiceIntegration.initDefaultConfig();
      service = await ServiceIntegration.getByServiceName(serviceName);

      if (!service) {
        throw new BusinessError('服务配置不存在且无法创建默认配置');
      }
    }

    res.json(success(service, '获取服务配置成功'));
  })
);

// 更新服务配置
router.put('/admin/:serviceName',
  authenticateAdmin,
  [
    body('display_name')
      .optional()
      .isLength({ max: 100 })
      .withMessage('显示名称不能超过100个字符'),
    body('base_url')
      .optional()
      .isURL()
      .withMessage('基础URL格式不正确'),
    body('api_key')
      .optional()
      .isLength({ max: 500 })
      .withMessage('API密钥不能超过500个字符'),
    body('api_config')
      .optional()
      .isObject()
      .withMessage('API配置必须是对象')
  ],
  catchAsync(async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      throw new BusinessError('参数验证失败', errors.array());
    }

    const { serviceName } = req.params;
    const updateData = req.body;

    console.log(`📝 更新服务配置请求: ${serviceName}`, updateData);

    let service = await ServiceIntegration.getByServiceName(serviceName);

    if (!service) {
      // 如果记录不存在，创建新记录
      const createData = {
        service_name: serviceName,
        display_name: updateData.display_name || serviceName,
        ...updateData
      };
      console.log(`📝 创建新记录数据:`, createData);
      service = await ServiceIntegration.create(createData);
      console.log(`✅ 创建新的服务配置: ${serviceName}`, service.toJSON());
    } else {
      // 如果记录存在，更新记录
      console.log(`📝 更新现有记录:`, service.toJSON());
      await service.update(updateData);
      console.log(`✅ 更新服务配置: ${serviceName}`, service.toJSON());
    }

    // 重新获取更新后的记录
    const updatedService = await ServiceIntegration.getByServiceName(serviceName);
    console.log(`📝 最终返回数据:`, updatedService.toJSON());

    res.json(success(updatedService, '服务配置保存成功'));
  })
);

// 测试服务连接
router.post('/admin/:serviceName/test',
  authenticateAdmin,
  [
    body('api_name')
      .notEmpty()
      .withMessage('API名称不能为空'),
    body('test_params')
      .optional()
      .isObject()
      .withMessage('测试参数必须是对象')
  ],
  catchAsync(async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      throw new BusinessError('参数验证失败', errors.array());
    }

    const { serviceName } = req.params;
    const { api_name, test_params = {} } = req.body;
    
    const service = await ServiceIntegration.getByServiceName(serviceName);
    if (!service) {
      throw new BusinessError('服务配置不存在');
    }
    

    
    if (!service.base_url) {
      throw new BusinessError('基础URL未配置');
    }
    
    const apiConfig = service.api_config[api_name];
    if (!apiConfig) {
      throw new BusinessError(`API配置不存在: ${api_name}`);
    }
    
    try {
      // 构建请求URL
      const baseUrl = service.base_url.replace(/\/$/, '');
      const path = apiConfig.path.startsWith('/') ? apiConfig.path : `/${apiConfig.path}`;
      const url = `${baseUrl}${path}`;
      
      // 构建请求配置
      const requestConfig = {
        method: apiConfig.method || 'GET',
        url,
        timeout: config.serviceIntegration.timeout,
        headers: {
          'Content-Type': 'application/json'
        }
      };
      
      // 添加API密钥 - 根据PRD要求使用x-api-key请求头
      if (service.api_key) {
        requestConfig.headers['x-api-key'] = service.api_key;
      }
      
      // 添加请求参数
      if (apiConfig.method === 'GET') {
        requestConfig.params = test_params;
      } else {
        requestConfig.data = test_params;
      }
      
      // 发送请求
      const response = await axios(requestConfig);

      // 验证子系统K的响应格式 {code: 0, message: 'ok', data: {}}
      const responseData = response.data;
      if (typeof responseData !== 'object' || responseData.code !== 0) {
        throw new Error(`子系统K响应格式错误: ${JSON.stringify(responseData)}`);
      }

      // 更新测试结果
      const testResult = {
        success: true,
        status: response.status,
        message: '连接测试成功',
        data: responseData,
        tested_at: new Date()
      };
      
      await service.update({
        last_test_time: new Date(),
        last_test_result: testResult
      });
      
      res.json(success(testResult, '连接测试成功'));
      
    } catch (error) {
      console.error('服务连接测试失败:', error);
      
      const testResult = {
        success: false,
        message: error.response?.data?.message || error.message || '连接测试失败',
        status: error.response?.status,
        tested_at: new Date()
      };
      
      await service.update({
        last_test_time: new Date(),
        last_test_result: testResult
      });
      
      throw new BusinessError(`连接测试失败: ${testResult.message}`);
    }
  })
);

// 调用外部API（供其他模块使用）
router.post('/call/:serviceName/:apiName',
  authenticateAdmin,
  catchAsync(async (req, res) => {
    const { serviceName, apiName } = req.params;
    const { params = {} } = req.body;
    
    const service = await ServiceIntegration.getByServiceName(serviceName);
    if (!service) {
      throw new BusinessError('服务配置不存在');
    }
    

    
    const apiConfig = service.api_config[apiName];
    if (!apiConfig) {
      throw new BusinessError(`API配置不存在: ${apiName}`);
    }
    
    try {
      // 构建请求URL
      const baseUrl = service.base_url.replace(/\/$/, '');
      const path = apiConfig.path.startsWith('/') ? apiConfig.path : `/${apiConfig.path}`;
      const url = `${baseUrl}${path}`;
      
      // 构建请求配置
      const requestConfig = {
        method: apiConfig.method || 'GET',
        url,
        timeout: config.serviceIntegration.timeout,
        headers: {
          'Content-Type': 'application/json'
        }
      };
      
      // 添加API密钥 - 根据PRD要求使用x-api-key请求头
      if (service.api_key) {
        requestConfig.headers['x-api-key'] = service.api_key;
      }
      
      // 添加请求参数
      if (apiConfig.method === 'GET') {
        requestConfig.params = params;
      } else {
        requestConfig.data = params;
      }
      
      // 发送请求
      const response = await axios(requestConfig);

      // 验证子系统K的响应格式 {code: 0, message: 'ok', data: {}}
      const responseData = response.data;
      if (typeof responseData !== 'object' || responseData.code !== 0) {
        throw new Error(`子系统K响应格式错误: ${JSON.stringify(responseData)}`);
      }

      res.json(success(responseData, 'API调用成功'));
      
    } catch (error) {
      console.error('API调用失败:', error);
      throw new BusinessError(`API调用失败: ${error.response?.data?.message || error.message}`);
    }
  })
);

// 使用SystemKClient调用子系统K API（推荐使用）
router.post('/system-k/:apiName',
  authenticateAdmin,
  catchAsync(async (req, res) => {
    const { apiName } = req.params;
    const { params = {} } = req.body;

    const service = await ServiceIntegration.getByServiceName('system_k');
    if (!service) {
      throw new BusinessError('子系统K配置不存在');
    }

    const client = new SystemKClient(service.base_url, service.api_key);

    try {
      let result;

      switch (apiName) {
        case 'getExpertList':
          const expertListPath = service.api_config.getExpertList?.path || '/api/experts';
          result = await client.getExpertList(expertListPath, params);
          break;
        case 'getQaDetail':
          if (!params.request_id) {
            throw new BusinessError('缺少request_id参数');
          }
          const qaDetailPath = service.api_config.getQaDetail?.path || '/api/qa/{request_id}';
          result = await client.getQaDetail(qaDetailPath, params.request_id);
          break;
        case 'getExpertDetail':
          if (!params.expertId) {
            throw new BusinessError('缺少expertId参数');
          }
          const expertDetailPath = service.api_config.getExpertList?.path || '/api/experts';
          result = await client.getExpertDetail(expertDetailPath, params.expertId);
          break;
        case 'testConnection':
          // 对于测试连接，我们可以使用专家列表API来测试
          const testPath = service.api_config.getExpertList?.path || '/api/experts';
          result = await client.testConnection(testPath);
          break;
        default:
          throw new BusinessError(`不支持的API: ${apiName}`);
      }

      res.json(success(result, 'API调用成功'));

    } catch (error) {
      console.error(`子系统K API调用失败 [${apiName}]:`, error);
      throw new BusinessError(`子系统K API调用失败: ${error.message}`);
    }
  })
);

// 清除图片URL模板缓存
router.post('/admin/clear-image-cache',
  authenticateAdmin,
  catchAsync(async (req, res) => {
    clearImageUrlTemplateCache();
    res.json(success(null, '图片URL模板缓存已清除'));
  })
);

// 初始化默认配置
router.post('/admin/init',
  authenticateAdmin,
  catchAsync(async (req, res) => {
    await ServiceIntegration.initDefaultConfig();
    res.json(success(null, '默认配置初始化成功'));
  })
);

export default router;
